package kroketwebspring.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kroketwebspring.dao.ProductDAO;
import kroketwebspring.dao.ProductDAOImpl;
import kroketwebspring.domain.Product;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class ProcessProductsController extends AbstractController {
	private ProductDAO productDAO;
	
	public void setProductDAO(ProductDAOImpl productDAO) {
		this.productDAO = productDAO;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map m 				= new HashMap();
		HttpSession session = request.getSession(true);
		
		// Get the parameters
		String sOrder = request.getParameter("ord");
		String sPage = request.getParameter("pag");
		String sAmount = request.getParameter("amo");
		int amount = Integer.parseInt(sAmount);
		
		// Process the orderstring
		char order;
		if (sOrder.equals("price")) {
			order = 'P';
		} else if (sOrder.equals("stock")) {
			order = 'S';
		} else {
			order = 'N';
		}

		// Get total products count from db and calulate the total amount of pages
		int totalProducts = productDAO.getProductCount();
		int totalPages = (int)Math.ceil((double)totalProducts/(double)amount);
		
		// Process the pagination vars
		int page = 1;
		if (sPage != null) {
			page = Integer.parseInt(sPage);
			if (page <= 0) {
				page = 1;
			} else if (page > totalPages) {
				page = totalPages;
			}
		}
		
		// calculate the start of the query
		int start = (page - 1) * amount;
		
		// Get products from db
		List<Product> products = productDAO.getSortedProducts(order, start, amount);
		
		// Get products from session
		ArrayList<Product> shoppingCartProducts = productDAO.getProductsArrayList(session);
		
		// Assign vars to model
		m.put("order", sOrder);
		m.put("page", sPage);
		m.put("amount", sAmount);
		m.put("totalPages", totalPages);
		m.put("products", products);
		m.put("shoppingCartProducts", shoppingCartProducts);
		
		// Return model and view
		return new ModelAndView("productsList", m);
	}

}
